package com.llkj.qingnianguoxue.zhuanlan;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.llkj.qingnianguoxue.R;
import com.llkj.qingnianguoxue.base.BaseActivity;
import com.llkj.qingnianguoxue.base.ConstantUserInfo;
import com.llkj.qingnianguoxue.base.MyApplication;
import com.llkj.qingnianguoxue.bean.ResponseBean;
import com.llkj.qingnianguoxue.bean.ZhiBoDetailBean;
import com.llkj.qingnianguoxue.http.HttpMethod;
import com.llkj.qingnianguoxue.login.LoginActivity;
import com.llkj.qingnianguoxue.util.DialogUtil;
import com.llkj.qingnianguoxue.util.GsonUtil;
import com.llkj.qingnianguoxue.util.ImageLoadingUtil;
import com.llkj.qingnianguoxue.util.MyShare;
import com.llkj.qingnianguoxue.util.PayMethodViewUtil;
import com.llkj.qingnianguoxue.util.StringUtils;
import com.llkj.qingnianguoxue.util.ToastUtil;

/**
 * 预约直播专栏
 */
public class BookZhiBoActivity extends BaseActivity implements View.OnClickListener, MyShare.ShareResultCallback,PayMethodViewUtil.PaySuccessListener {
    private static final int REQUEST_LOGIN_CODE = 9934;
    private ImageView ivPic;//直播图片
    private TextView tvDetailTitle, tvTime, tvState;//直播标题，直播时间，直播状态
    private TextView tvDescription;//直播简介
    private TextView tvPrice;//预约价格
    private String mDetailId, mZhiBoTime;//直播id,直播距离时间
    private long startLong;
    private boolean isBooking;//是否预约
    private String mLiveUrl;//直播封面图片
    private PayMethodViewUtil payMethodViewUtil;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_book_zhi_bo);
        setTitle("直播专栏", true, TITLE_TYPE_IMG, R.drawable.icon_back, true, TITLE_TYPE_IMG, R.drawable.icon_book_share);
        Intent intent = getIntent();
        Bundle bundle = intent.getExtras();
        if (bundle != null) {
            mDetailId = bundle.getString("id");
        }

        initView();
        payMethodViewUtil = new PayMethodViewUtil(this,this);

        getDetail();
    }

    private void initView() {
        initStatusbar(TSATUSBAR_TYPE_BLACK_TEXT,rlTitle,R.color.gray_bar);
//        FrameLayout titleView = (FrameLayout) findViewById(R.id.fl_title);
//        LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) titleView.getLayoutParams();
//        params.width = DisplayUtil.getDensityWdith(this);
//        params.height = params.width * 182 / 750;
        ivPic = (ImageView) findViewById(R.id.ivPic);
        tvDetailTitle = (TextView) findViewById(R.id.tv_detail_title);
        tvTime = (TextView) findViewById(R.id.tv_date);
        tvState = (TextView) findViewById(R.id.tv_state);
        tvDescription = (TextView) findViewById(R.id.tv_detail);
        tvPrice = (TextView) findViewById(R.id.tv_price);
        tvPrice.setText(String.format(getString(R.string.pay_format), String.valueOf(50.00)));

        tvState.setVisibility(View.GONE);
        tvState.setOnClickListener(this);
    }

    @Override
    protected void rightDoWhat() {
        super.rightDoWhat();
        if(StringUtils.isEmpty(mLiveUrl)){
            return;
        }
        //分享
        String title = tvDetailTitle.getText().toString();
        String linkUrl = String.format(HttpMethod.SHARE_LIVE, mDetailId);
        String description = tvDescription.getText().toString();
        DialogUtil.showShareDialog(this, title, description, mLiveUrl, linkUrl, this,1);
    }

    @Override
    public void onClick(View v) {
        if(isBooking){
            return;
        }
        boolean isLogin = MyApplication.getInstance().sputil.getBoolean(ConstantUserInfo.ISLOGIN);
        if (!isLogin) {
            dialogConfirm(null, null, null, null).show();
            return;
        }
        switch (v.getId()) {
            case R.id.tv_state:
                payMethodViewUtil.showPayMethodDialog("0.1");
//                loadWaitDialog();
//                HttpMethod.liveOrder(this, this, mDetailId);
                break;
        }
    }

    @Override
    public void shareResultCallBack(int result) {
        switch (result) {
            case 1:
                break;
            case 2:
                break;
            case 3:
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        payMethodViewUtil.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK && requestCode == REQUEST_LOGIN_CODE) {
            getDetail();
        }
    }

    @Override
    public void paySucessResponse(int type) {
        //处理三方支付成功后的操作
        if(type!=1){//三方支付

        }else{//余额

        }
    }
    @Override
    protected void dialogRightBtn() {
        super.dialogRightBtn();
        startActivityForResult(LoginActivity.class, new Bundle(), REQUEST_LOGIN_CODE);
    }

    private void getDetail(){
        loadWaitDialog();
        HttpMethod.liveDetails(this, this, mDetailId, "1");
    }
    @Override
    protected void onhttpSuccess(String data, int method) {
        super.onhttpSuccess(data, method);
        if (method == HttpMethod.HTTP_LIVE_DETAILS) {
            ZhiBoDetailBean detailBean = GsonUtil.GsonToBean(data, ZhiBoDetailBean.class);
            if (detailBean != null) {
                mLiveUrl =detailBean.getDetails().getImg();
                ImageLoadingUtil.loadingUrl(ivPic,"http://qingchunguoxue.apptiming.com/Uploads/2017-09-01/59a92b8db5f01.jpg");
//                ImageLoadingUtil.loadingUrl(ivPic,mLiveUrl);
                tvDetailTitle.setText(detailBean.getDetails().getTitle());
                mZhiBoTime = detailBean.getDetails().getLive_time();
                tvTime.setText(mZhiBoTime);
                tvDescription.setText(detailBean.getDetails().getAbstractX());

                tvState.setVisibility(View.VISIBLE);
                if("1".equals(detailBean.getDetails().getIs_order())){
                    isBooking = true;
                }

                if (!StringUtils.isEmpty(mZhiBoTime) && isBooking) {
//                    try {
//                        SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//                        Date date = sdf1.parse(mZhiBoTime);
                        startLong = Long.parseLong(detailBean.getDetails().getCountdown());

                        if (startLong > 1) {
                            handler.postDelayed(runnable, 1000);
                        }else{
                            startZhiBo();
                        }
//                    } catch (ParseException e) {
//                        e.printStackTrace();
//                    }
                }
            }
        } else if (method == HttpMethod.HTTP_LIVE_ORDER) {//预约直播
            ToastUtil.makeLongText(this, "预约成功");
            isBooking = true;
            ResponseBean responseBean = GsonUtil.GsonToBean(data, ResponseBean.class);
            if (responseBean != null) {
                String time = responseBean.getResidue_time();
                startLong = Long.parseLong(time);
            }
            if (startLong > 1) {
                handler.postDelayed(runnable, 1000);
            }else{
                startZhiBo();
            }
        }
    }

    @Override
    protected void onhttpFailed(String message, int method) {
        super.onhttpFailed(message, method);
        if (!StringUtils.isEmpty(message)) {
            ToastUtil.makeLongText(this, message);
        }
    }

    @Override
    protected void onStop() {
        super.onStop();
//        try {
//            handler.removeCallbacks(runnable);
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
    }

    Handler handler = new Handler();
    Runnable runnable = new Runnable() {
        @Override
        public void run() {
            long timeLong = startLong--;
            int day = (int) (timeLong / (24 * 60 * 60));
            int hours = (int) ((timeLong%(24 * 60 * 60)) / (60 * 60));
            int minutes = (int) ((timeLong%(24 * 60 * 60) % (60 * 60)) / (60));
            int seconds = (int) ((timeLong % (60)));
            String time = "";
            if (day > 0) {
                time = day + "天 ";
            }
            time = time + hours + ":" + minutes + ":" + seconds;
            tvState.setText(time);
            handler.postDelayed(this, 1000);

            if(startLong<=0){
                try {
                    handler.removeCallbacks(runnable);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                startZhiBo();
            }
        }
    };

    private void startZhiBo(){
        Bundle bundle = new Bundle();
        bundle.putString("id",mDetailId);
        bundle.putString("type", "1");
        startActivity(ZhiBoDetailActivity.class, bundle);
        finish();
    }
}
